<template>
      <div>
       <!-- 选取素材图片的对话框 -->
      <el-dialog
      title="提示"
      :visible.sync="dialogVisible"
      width="60%"
      >
      <!-- 展示素材图片 -->
      <ul>
        <li class="image-box" v-for="item in imageList" :key="item.id">
          <img :src="item.url" alt="" @click="clkImage">
        </li>
      </ul>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="imageOk">确 定</el-button>
      </span>
    </el-dialog>
    <!--  -->
        <el-card class="box-cord">
            <div slot="header" class="clearfix">
                <span>修改文章 <span>表单是否被修改{{editFormDirty}}</span></span>
                <el-button @click="editArticle(true)" style="float:right" type='danger'>存入草稿</el-button>
                 <el-button @click="editArticle(false)" style="float:right; margin-right:10px;" type='primary'>发布</el-button>
            </div>

            <el-form ref="editFormRef" :model="editForm" :rules="editFormRules">
                <el-form-item label='标题:' label-width="100px" prop="title">
                    <el-input v-model="editForm.title"></el-input>
                </el-form-item>
                <el-form-item label='内容:' label-width="100px" prop="content">
                  <quillEditor v-model="editForm.content"></quillEditor>
                   <!-- <comLogin></comLogin> -->
                </el-form-item>

                <el-form-item label='封面:' label-width="100px" >
                    <el-radio-group v-model="editForm.cover.type">
                        <el-radio :label='1'>单图</el-radio>
                        <el-radio :label='3'>三图</el-radio>
                        <el-radio :label='0'>无图</el-radio>
                        <el-radio :label='-1'>自动</el-radio>
                    </el-radio-group>
<!--              图片                                    -->
                      <ul>
                        <li class="uploadbox" v-for="item in covernum" :key="item"
                        @click="showDiaolog(item)">
                          <span>点击图标选择图片</span>
                          <img v-if="editForm.cover.images[item-1]" :src="editForm.cover.images[item-1]" alt="" />
                          <div v-else class="el-icon-picture-outline"></div>
                        </li>
                      </ul>

<!--              图片                                    -->
                </el-form-item>
                <el-form-item label='频道:' label-width="100px" prop="channel_id">
                    <el-select
                    clearable
                    v-model="editForm.channel_id" placeholder="请选择">
                        <el-option
                        v-for="item in channelList"
                        :key="item.id"
                        :label='item.name'
                        :value='item.id'
                        ></el-option>
                        </el-select>
                </el-form-item>
                <el-form-item label=''></el-form-item>
            </el-form>
        </el-card>
    </div>
</template>

<script>
// 富文本编辑器
import { quillEditor } from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

export default {
  name: 'ArticleeditCom',
  computed: {
    covernum () {
      if (this.editForm.cover.type >= 0) {
        return this.editForm.cover.type
      }
      return 0
    }
  },

  // -----------------------------
  components: {
    // 私有方式注册 富文本编辑器
    quillEditor
  },
  created () {
    this.getChannelList() // 获取频道信息
    this.getArticle()
  },
  beforeRouteLeave (to, from, next) {
    if (this.editFormDirty) {
    // 如果form表单被修改了，本身不保存，发生离开动作就要给与提示
      this.$confirm('当前表单已经被修改了，确认不保存要离开么?', '离开', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return next() // 放行
      }).catch(() => {
        return next(false) // 阻止执行
      })
    } else {
      return next() // 放行
    }
  },
  methods: {
    // --------------tu----------------
    clearImag () {
      this.materialUrl = ''
      // 先给素材图片去除效果
      var lis = document.querySelectorAll('.image-box')
      for (var i = 0; i < lis.length; i++) {
        lis[i].style.border = ''
      }
    },
    // 确定选中
    imageOk () {
      if (this.materialUrl) {
        // 把选择好的图片的地址赋予给 editForm.cover.images成员里边
        this.editForm.cover.images[this.xu] = this.materialUrl
        // 关闭对话框
        this.dialogVisible = false
        // 清除全部都不选中
        this.clearImage()
      }
    },
    // 选取素材图片
    clkImage (evt) {
      this.clearImag()
      // 给当前选中的素材设置高亮显示
      evt.target.parentNode.style.border = '2px solid orange'
      this.materialUrl = evt.target.src
    },
    // 获取素材图片
    getImageList () {
      var pro = this.$http.get('/user/images', {
        params: this.querycdt
      })
      pro
        .then(result => {
          this.imageList = result.data.data.results
        })
        .catch(err => {
          return this.$message.error('获取图片列表失败' + err)
        })
    },
    // 控制素材对话框的显示
    showDiaolog (n) {
      // 自动减少一位
      this.order = n - 1

      this.dialogVisible = true
      this.getImageList()
    },
    // --------------tu----------------
    editFormWatch () {
      this.$watch(
        'editForm',
        function () {
          this.editFormDirty = true
        },
        { deep: true }
      )
    },
    // 获取文章信息
    getArticle () {
      var pro = this.$http.get(`/articles/${this.aid}`)
      pro
        .then(result => {
          // 把获得的文章信息赋予给editForm对象

          this.editForm = result.data.data

          //   开始监听
          this.$nextTick(() => {
            this.editFormWatch()
          })
        })
        .catch(err => {
          return this.$message.error('修改文章错误' + err)
        })
    },
    // 修改文章
    editArticle (flag) {
      this.$refs.editFormRef.validate(valid => {
        // axios.post(地址, 请求体数据, 请求字符串)

        var pro = this.$http.put(`/articles/${this.editForm.id}`, this.editForm, { params: { draft: flag } })
        pro
          .then(result => {
            this.$message.success('修改文章成功!')
            this.editFormDirty = false
            // 导航到 文章列表页面
            this.$router.push({ name: 'article' })
          })
          .catch(err => {
            return this.$message.error('修改文章错误' + err)
          })
      })
    },
    getChannelList () {
      var pro = this.$http.get('/channels')
      pro
        .then(result => {
          // 把获得好的频道信息赋予给 channelList 成员
          this.channelList = result.data.data.channels
        })
        .catch(err => {
          console.log(err)
        })
    }
  },
  data () {
    return {
      //  记录选好的素材序号
      materialUrl: '',
      // 记录选择的素材序号
      xu: 0, // 素材图片
      imageList: [],
      querycdt: {
        collect: false,
        page: 1,
        per_page: 18
      },
      // 素材图片是否显示
      dialogVisible: false,
      // 监听  当前表单是否发生变化
      editFormDirty: false,
      // 路由id
      aid: this.$route.params.aid,
      // 用户使用的频道列表信息
      channelList: [],
      //  表单规则制定
      editFormRules: {
        title: [
          { required: true, message: '标题必填', trigger: 'blur' },
          { min: 5, max: 30, message: '标题内容介于5到30个字符之间', trigger: 'blur' }
        ],
        content: [
          // 因为是富文本编辑器 此处内容校验要通过validate方法校验
          { required: true, message: '内容必填', trigger: 'blur' }
        ],
        channel_id: [
          { required: true, message: '频道必填', trigger: 'change' }
        ]
      },
      // 修改文章表单对象
      editForm: {
        title: '',
        channel_id: '',
        content: '',
        cover: {
          type: '',
          images: ''
        }

      }
    }
  }
}
</script>

<style lang='less'>
  .ql-editor {
    height: 200px;
  }
</style>
<style  lang='less' scoped>
    .image-box {
      list-style: none;
      width: 200px;
      height: 140px;
      background-color: #fff;
      margin: 10px;
      float: left;
      border: 1px solid #eee;
      cursor:pointer;
      box-sizing:border-box;
      img {
        width: 100%;
        height: 100%;
      }
    }
    .uploadbox {
      list-style: none;
      width: 200px;
      height: 200px;
      margin: 10px;
      float: left;
      cursor: pointer;
      border: 1px solid #eee;
      span {
        width: 200px;
        height: 50px;
        line-height: 50px;
        display: block;
        text-align: center;
      }
      div {
        width: 200px;
        height: 150px;
        font-size: 100px;
        display: flex;
        justify-content: center;
        align-items: center;
        background-color: #fff;
      }
      img{
        width: 200px;
        height: 150px;
      }
    }
</style>
